<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="lib/jquery/jquery-3.3.1.min.js"></script>
    <script src="js/ol-debug.js"></script>
    <link rel="stylesheet" href="js/ol.css">
    <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.css">
    <script src="lib/bootstrap/js/bootstrap.js"></script>
    <script src="lib/layer/layer.js"></script>
    <link rel="stylesheet" href="js/ol3-layerswitcher.css">
    <script src="js/ol3-layerswitcher.js"></script>

    <style>
        #marker {
            width: 20px;
            height: 20px;
            border: 1px solid #088;
            border-radius: 10px;
            background-color: #0FF;
            opacity: 0.5;
        }
        #vienna {
            text-decoration: none;
            color: white;
            font-size: 11pt;
            font-weight: bold;
            text-shadow: black 0.1em 0.1em 0.2em;
        }
        .popover{
            max-width:300px;
            min-width: 100px;

        }
        .popover-content {
            min-width: 700px;
            max-width: 1000px;

        }
        #map-switch{
            position:absolute;
            top: 50px;
            right: 50px;
            z-index: 10;
            padding: 10px;
            background-color: #ddccac;
            /*阴影*/
            box-shadow: 5px 5px 3px #888888;
            /*边框*/
            border:1px solid #9d9d9d;
            /*圆角*/
            border-radius:10px;
        }
        #map-measure{
            position: absolute;
            z-index: 10;
            left: 100px;
            top:30px;
        }
        /*测量样式*/
        .tooltip {
            position: relative;
            background: rgba(0, 0, 0, 0.5);
            border-radius: 4px;
            color: white;
            padding: 4px 8px;
            opacity: 0.7;
            white-space: nowrap;
        }
        .tooltip-measure {
            opacity: 1;
            font-weight: bold;
        }
        .tooltip-static {
            background-color: #ffcc33;
            color: black;
            border: 1px solid white;
        }
        .tooltip-measure:before,
        .tooltip-static:before {
            border-top: 6px solid rgba(0, 0, 0, 0.5);
            border-right: 6px solid transparent;
            border-left: 6px solid transparent;
            content: "";
            position: absolute;
            bottom: -6px;
            margin-left: -7px;
            left: 50%;
        }
        .tooltip-static:before {
            border-top-color: #ffcc33;
        }
    </style>
    <link rel="stylesheet" href="lib/bootstrap/switch/bootstrap-switch.min.css">
    <script src="lib/bootstrap/switch/bootstrap-switch.min.js"></script>

</head>
<body>

<div id="map" style="width: 100%">
    <!--弹出框-->
    <div style="display: none;">
        <!-- Clickable label for Vienna -->
        <a class="overlay" id="vienna" target="_blank" href="http://en.wikipedia.org/wiki/Vienna">Vienna</a>
        <div id="marker" title="Marker"></div>
        <!-- Popup -->
        <div id="popup" title="基本信息"></div>
    </div>
    <!--地图图层控制-->
    <div id="map-switch">
        <div>
            <input type="checkbox" name="mapswitch" value="点" checked="checked"> 点
        </div>
        <div>
            <input type="checkbox" name="mapswitch" value="线" checked="checked"> 线
        </div>
        <div>
            <input type="checkbox" name="mapswitch" value="面"checked="checked"> 面
        </div>
    </div>
    <!--地图测量-->
    <div id="map-measure">
        <button  id="measure-length" type="button" class="btn btn-info">长度测量</button>
        <button id="measure-area" class="btn btn-info">面积测量</button>
        <button id="measure-cancel" class="btn btn-info">清除</button>
    </div>
</div>


<script type="text/javascript">
    var webip="http://localhost:";
    var gisip="http://localhost:";
    var webport="8080/";
    var gisport="8080/";

    $('#map-switch input').change(function () {
        //var a= $(this).attr();
        var value=$(this).val();
        var ischeck=this.checked;
        switch(value)
        {
            case "点":
                if (ischeck==true)
                {
                    //map.addLayer(pointVectorLayer);
                    pointVectorLayer.setVisible(true);
                }
                else
                {
                    //map.removeLayer(pointVectorLayer);
                    pointVectorLayer.setVisible(false);
                }
                break;
            case "线":
                if (ischeck==true)
                {
                    map.addLayer(polylineVectorLayer);
                }
                else
                {
                    map.removeLayer(polylineVectorLayer);
                }
                break;
            case "面":
                if (ischeck==true)
                {
                    map.addLayer(polylgonVectorLayer);
                }
                else
                {
                    map.removeLayer(polylgonVectorLayer);
                }
                break;
            default:
                break;
        }
    });


    $("#map-measure button").click(function (e) {
        measureSource.clear();
        map.removeOverlay(measureTooltip);
        var type=$(this).text();
        if (type=="长度测量")
        {
            startMeasure("LineString")
        }
        else if (type=="面积测量")
        {
            startMeasure("Polygon")
        }
        else if(type=="清除")
        {

        }
    });

</script>
<script>
    /////////////////////////////////////////////////////////////////////////////////////////////////////基本图层//////////////////////////////////////////////////
    /*视图*/
    var view=new ol.View({
        // 设置成都为地图中心
        center: ol.proj.transform([508881,299705],"EPSG:3857","EPSG:3857"),
        zoom: 19
    });
    /*切片图层*/
    var tiledwms = new ol.layer.Tile({
        //visible: false,
        source: new ol.source.TileWMS({
            url: gisip+gisport+'geoserver/xcy/wms',
            params: {'FORMAT': "image/png",
                'VERSION': '1.1.1',
                tiled: true,
                "STYLES": '',
                "LAYERS": 'xcy:17'
                //"exceptions": 'application/vnd.ogc.se_inimage',
                //tilesOrigin: 8176078.237520734 + "," + 704818.0275364731
            }
        })
    });
    /*矢量图层*/
    var pointTypename="xcy:point";
    var pointVectorSource = new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        url: function(extent) {
            //return 'http://localhost:8080/geoserver/wfs?service=WFS&version=1.1.0&request=GetFeature&typename=xcy:point&outputFormat=application/json&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';
            //return 'http://localhost:8080/geoserver/xcy/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=xcy:point&maxFeatures=50&outputFormat=application%2Fjson';
            return  gisip+gisport+'geoserver/xcy/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName='+pointTypename+'&outputFormat=application%2Fjson';
        },
        strategy: ol.loadingstrategy.bbox
    });
    var pointVectorLayer = new ol.layer.Vector({
        title:"点",
        source: pointVectorSource,
        renderMode:'image',
        style: new ol.style.Style({
            image:new ol.style.Circle({
                radius: 5,
                fill: new ol.style.Fill({
                    color: "#389BCD",
                    opacity: 0.5
                })
            })
        })
    });

    var polylineTypename="xcy:polyline";
    var polylineVectorSource = new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        url: function(extent) {
            return gisip+gisport+ 'geoserver/xcy/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName='+polylineTypename+'&outputFormat=application%2Fjson';
        },
        strategy: ol.loadingstrategy.bbox
    });
    var polylineVectorLayer = new ol.layer.Vector({
        title:"线",
        source: polylineVectorSource,
        renderMode:'image',
        style: new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: '#06caba',
                width: 2
            })
        })
    });

    var polygonTypename="xcy:polygon";
    var polygonVectorSource = new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        url: function(extent) {
            return gisip+gisport+'geoserver/xcy/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName='+polygonTypename+'&outputFormat=application%2Fjson';
        },
        strategy: ol.loadingstrategy.bbox
    });
    var polylgonVectorLayer = new ol.layer.Vector({
        title:"面",
        source: polygonVectorSource,
        renderMode:'image',
        style: new ol.style.Style({
            image: new ol.style.Circle({
                fill: new ol.style.Fill({
                    color: 'rgba(255,0,255,0.4)'
                }),
                stroke: new ol.style.Stroke({
                    color: '#cc3540',
                    width: 1.25
                }),
                radius: 5
            }),
            stroke: new ol.style.Stroke({
                color: '#dd9910',
                width: 1
            }),
            fill: new ol.style.Fill({
                color: '#dd12b7'
            })
        })
    });

    /*矢量测量草图图层*/
     var measureSource=new ol.source.Vector();
    var mmeasureVectorlayer = new ol.layer.Vector({
        source:measureSource,
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.2)'
            }),
            stroke: new ol.style.Stroke({
                color: '#ffcc33',
                width: 2
            }),
            image: new ol.style.Circle({
                radius: 7,
                fill: new ol.style.Fill({
                    color: '#ffcc33'
                })
            })
        })
    });


    /*地图map*/
    var ii = layer.load();
    var map = new ol.Map({
        controls: ol.control.defaults().extend([
/*
            new ol.control.FullScreen(),
*/
/*            new ol.control.MousePosition({
                coordinateFormat: ol.coordinate.createStringXY(4),
                projection: 'EPSG:3857',
                className: 'custom-mouse-position',
                target: document.getElementById('mouse-position')
            }) ,*/
            //new ol.control.OverviewMap({  }),
/*            new ol.control.Rotate({
                autoHide:false
            }),*/
            new ol.control.ScaleLine({  }),
            //new ol.control.ZoomSlider({  }),
            //new ol.control.ZoomToExtent({  })
        ]),
        layers: [
            polylineVectorLayer,
            pointVectorLayer,
            polylgonVectorLayer,
            mmeasureVectorlayer
        ],
        view:view,
        target: 'map'
    });
    /////////////////////////////////////////////////////////////////////////////////////////////////////辅助控件//////////////////////////////////////////////////

/*    var layerSwitcher = new ol.control.LayerSwitcher();
    map.addControl(layerSwitcher);*/

    /*layer加载监听*/
    var listenerKey = polylineVectorSource.on('change', function(e) {
        if (polylineVectorSource.getState() == 'ready') {
            layer.close(ii);
            ol.Observable.unByKey(listenerKey);
            var features= pointVectorSource.getFeatures();
        }
    });

    /*overlay*/
    // Popup showing the position the user clicked
    var popup = new ol.Overlay({
        element: document.getElementById('popup'),
        autoPan:true,
        autoPanMargin:100,
        positioning:'center-right'
    });
    map.addOverlay(popup);

    /*select*/
    var selectSingleClick = new ol.interaction.Select({
        layers:[polylgonVectorLayer,
        polylineVectorLayer,
        pointVectorLayer]
    });
    map.addInteraction(selectSingleClick);
    selectSingleClick.on('select', function(e) {
        polygonVectorSource.clear();
        var features=e.target.getFeatures().getArray();
        var element = popup.getElement();
        if (features.length>0)
        {

            var feature=features[0];
            var type=feature.getGeometry().getType();
            var property=feature.getProperties();
            //
            var coordinates=feature.getGeometry().getCoordinates()[0][0];
            for (var i=0;i<coordinates.length;i++)
            {
                var feature = new ol.Feature({
                    geometry: new ol.geom.Point(coordinates[i]),
                    name: 'My Polygon'
                });
                polygonVectorSource.addFeature(feature);
            }
            var coordinate = ol.extent.getCenter(feature.getGeometry().getExtent());
            var hdms="点名："+property["Text"];
            hdms=hdms+"<br/>";
            hdms = hdms+"图层名：:"+property["Layer"];
            hdms=hdms+"<br/>";
            hdms = hdms+"位置:"+coordinate[0]+"-"+coordinate[1];
            hdms=hdms+"<br/>";
            hdms=hdms+"<a href='echart.html' target='_blank'>详细信息</a>";

            $(element).popover('destroy');
            popup.setPosition(coordinate);
            // the keys are quoted to prevent renaming in ADVANCED mode.
            $(element).popover({
                'placement': 'top',
                'animation': false,
                'html': true,
                'content': hdms
            });
            $(element).popover('show');
        }
        else
        {
            $(element).popover('destroy');

        }

    });

    /*测量功能*/
    var measureTooltipElement;
    var measureTooltip;
    function startMeasure(type) {
       var draw = new ol.interaction.Draw({
            source: measureSource,
            type: type,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                }),
                stroke: new ol.style.Stroke({
                    color: 'rgba(0, 0, 0, 0.5)',
                    lineDash: [10, 10],
                    width: 2
                }),
                image: new ol.style.Circle({
                    radius: 5,
                    stroke: new ol.style.Stroke({
                        color: 'rgba(0, 0, 0, 0.7)'
                    }),
                    fill: new ol.style.Fill({
                        color: 'rgba(255, 255, 255, 0.2)'
                    })
                })
            }),
            stopClick:true,
            freehand:false
        });
        map.addInteraction(draw);
        if (measureTooltipElement) {
            measureTooltipElement.parentNode.removeChild(measureTooltipElement);
        }
        measureTooltipElement = document.createElement('div');
        measureTooltipElement.className = 'tooltip tooltip-measure';
        measureTooltip = new ol.Overlay({
            element: measureTooltipElement,
            offset: [0, -15],
            positioning: 'bottom-center'
        });
        map.addOverlay(measureTooltip);

        var listener;
        var sketch;
        draw.on('drawstart',
            function(evt) {
                map.removeInteraction(selectSingleClick);

                // set sketch
                sketch = evt.feature;

                /** @type {ol.Coordinate|undefined} */
                var tooltipCoord = evt.coordinate;

                listener = sketch.getGeometry().on('change', function(evt) {
                    var geom = evt.target;
                    var output;
                    if (geom instanceof ol.geom.Polygon) {
                        output = formatArea(geom);
                        tooltipCoord = geom.getInteriorPoint().getCoordinates();
                    } else if (geom instanceof ol.geom.LineString) {
                        output = formatLength(geom);
                        tooltipCoord = geom.getLastCoordinate();
                    }
                    measureTooltipElement.innerHTML = output;
                    measureTooltip.setPosition(tooltipCoord);
                });
            }, this);

        draw.on('drawend',
            function() {
                map.addInteraction(selectSingleClick);

                measureTooltipElement.className = 'tooltip tooltip-static';
                measureTooltip.setOffset([0, -7]);
                // unset sketch
                sketch = null;
                // unset tooltip so that a new one can be created
                measureTooltipElement = null;

                map.removeInteraction(draw);
            }, this);
    }
    /**
     * Format length output.
     * @param {ol.geom.LineString} line The line.
     * @return {string} The formatted length.
     */
    var formatLength = function(line) {
        //var length = ol.Sphere.getLength(line);
        var length = line.getLength();
        var output;
        if (length > 100) {
            output = (Math.round(length / 1000 * 100) / 100) +
                ' ' + 'km';
        } else {
            output = (Math.round(length * 100) / 100) +
                ' ' + 'm';
        }
        return output;
    };

    /**
     * Format area output.
     * @param {ol.geom.Polygon} polygon The polygon.
     * @return {string} Formatted area.
     */
    var formatArea = function(polygon) {
        var area = ol.Sphere.getArea(polygon);
        //var area =polygon.getArea();
        var output;
        if (area > 10000) {
            output = (Math.round(area / 1000000 * 100) / 100) +
                ' ' + 'km<sup>2</sup>';
        } else {
            output = (Math.round(area * 100) / 100) +
                ' ' + 'm<sup>2</sup>';
        }
        return output;
    };


</script>
</body>
</html>
